package com.sqllog.admin.sql.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sqllog.admin.framework.domain.request.PageDomain;
import com.sqllog.admin.framework.tools.SequenceUtil;
import com.sqllog.admin.sql.datasource.LogSaveDataSourceOption;
import com.sqllog.admin.sql.datasource.MongoDbSaveDataSourceOption;
import com.sqllog.admin.sql.entity.LogDatabaseManager;
import com.sqllog.admin.sql.mapper.LogDatabaseManagerMapper;
import com.sqllog.admin.utils.CommonUtils;
import com.sqllog.admin.utils.SpringContextUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * TODO
 *
 * @author chennengcheng
 * @date 2022-01-23 15:19
 * @remark
 */

@Service
public class LogDatabaseManagerService {

    @Resource
    private LogDatabaseManagerMapper logDatabaseManagerMapper;

    public PageInfo<LogDatabaseManager> selectByQueryName(PageDomain pageDomain, String queryName) {
        PageHelper.startPage(pageDomain.getPage(), pageDomain.getLimit());
        List<LogDatabaseManager> logDatabaseManagers = logDatabaseManagerMapper.selectByQueryName(queryName);
        return new PageInfo<>(logDatabaseManagers);
    }

    public static void main(String[] args) {
        int i = 2 % 5;
        System.out.println(i);
    }



    public List<LogDatabaseManager> selectByQueryName(String queryName) {
        return logDatabaseManagerMapper.selectByQueryName(queryName);
    }

    public LogDatabaseManager insert(String destination, String dataBaseName, String tableName, String month) {
        String queryName = CommonUtils.generateTableNameByYearOfMonth(dataBaseName, tableName, month);
        LogDatabaseManager logDatabaseManager = new LogDatabaseManager();
        logDatabaseManager.setDestination(destination);
        logDatabaseManager.setCreateDate(new Date());
        logDatabaseManager.setDatabaseName(dataBaseName);
        logDatabaseManager.setTableName(tableName);
        logDatabaseManager.setYearOfMonth(month);
        logDatabaseManager.setQueryName(queryName);
        logDatabaseManager.setUpdateDate(new Date());
        logDatabaseManager.setId(SequenceUtil.makeStringId());
        logDatabaseManager.setDelFlag("0");
        logDatabaseManagerMapper.insert(logDatabaseManager);
        return logDatabaseManager;
    }

    public int deleteById(String id) {
        LogDatabaseManager log = logDatabaseManagerMapper.getById(id);
        LogSaveDataSourceOption logSaveDataSourceOption = SpringContextUtils.getBean(MongoDbSaveDataSourceOption.class);
        logSaveDataSourceOption.deleteTable(log.getDatabaseName(), log.getTableName(), log.getYearOfMonth());
        return logDatabaseManagerMapper.deleteById(id);
    }
}
